'use client';

import * as React from 'react';
import Link from 'next/link';
import {
  Bot,
  Menu,
  Store,
  Plus,
  Zap,
  Plug,
  ChevronRight,
  Loader2,
  Icon,
  icons,
  Wallet,
  ChevronDown,
} from 'lucide-react';

import { NavAgents } from '@/components/sidebar/nav-agents';
import { NavUserWithTeams } from '@/components/sidebar/nav-user-with-teams';
import { RonqiLogo } from '@/components/sidebar/ronqi-logo';
import { CTACard } from '@/components/sidebar/cta';
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  SidebarRail,
  SidebarTrigger,
  useSidebar,
} from '@/components/ui/sidebar';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useEffect, useState } from 'react';
import { createClient } from '@/lib/supabase/client';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { useIsMobile } from '@/hooks/use-mobile';
import { Badge } from '../ui/badge';
import { cn } from '@/lib/utils';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useFeatureFlags } from '@/lib/feature-flags';
import { useCreateNewAgent } from '@/hooks/react-query/agents/use-agents';
import { Button } from '../ui/button';

export function SidebarLeft({
  ...props
}: React.ComponentProps<typeof Sidebar>) {
  const { state, setOpen, setOpenMobile } = useSidebar();
  const isMobile = useIsMobile();
  const [user, setUser] = useState<{
    name: string;
    email: string;
    avatar: string;
  }>({
    name: 'Loading...',
    email: 'loading@example.com',
    avatar: '',
  });

  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();
  const currentAgentType =
    searchParams.get('agentType') || localStorage.getItem('agentType');
  const currentSubPage = searchParams.get('subPage');
  const [expandedAgent, setExpandedAgent] = useState<string | null>(null);
  const { flags, loading: flagsLoading } = useFeatureFlags([
    'custom_agents',
    'agent_marketplace',
  ]);
  const customAgentsEnabled = flags.custom_agents;
  const marketplaceEnabled = flags.agent_marketplace;
  const createNewAgentMutation = useCreateNewAgent();
  const [showNewAgentDialog, setShowNewAgentDialog] = useState(false);

  useEffect(() => {
    const fetchUserData = async () => {
      const supabase = createClient();
      const { data } = await supabase.auth.getUser();

      if (data.user) {
        setUser({
          name:
            data.user.user_metadata?.name ||
            data.user.email?.split('@')[0] ||
            'User',
          email: data.user.email || '',
          avatar: data.user.user_metadata?.avatar_url || '',
        });
      }
    };

    fetchUserData();
  }, []);

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key === 'b') {
        event.preventDefault();
        setOpen(!state.startsWith('expanded'));
        window.dispatchEvent(
          new CustomEvent('sidebar-left-toggled', {
            detail: { expanded: !state.startsWith('expanded') },
          }),
        );
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [state, setOpen]);

  // 当选择了客服助理时自动展开子菜单
  useEffect(() => {
    if (currentAgentType) {
      const selectedAgent = FUNCTION_AGENTS.find(
        (agent) => agent.id === currentAgentType,
      );
      if (selectedAgent?.subpages) {
        setExpandedAgent(currentAgentType);
      }
    }
  }, [currentAgentType]);

  const handleCreateNewAgent = () => {
    createNewAgentMutation.mutate();
  };

  // 客服助理的子页面选项
  const CUSTOMER_SERVICE_SUBPAGES = [
    {
      id: 'rag',
      name: '知识库',
      path: '/knowledge',
      description: 'Retrieval Augmented Generation',
    },
    {
      id: 'ai-assist',
      name: 'AI辅助',
      // path: '/aiAssist',
      path: '/dashboard',
      description: 'AI assistance features',
    },
    {
      id: 'settings',
      name: '设置',
      path: '/modalSettings',
      // path: '/dashboard',
      description: 'Configuration settings',
    },
    {
      id: 'team-analytics',
      name: '团队分析',
      // path: '/teamAnalytics',
      path: '/dashboard',
      description: 'Team performance analytics',
    },
    {
      id: 'review-settings',
      name: '审查设置',
      path: '/dashboard',
    },
    {
      id: 'conversation-settings',
      name: '话术设置', // Script Settings
      path: '/dashboard',
    },
  ];

  // 定义功能代理接口
  interface FunctionAgent {
    id: string;
    name: string;
    description: string;
    icon: string | React.ReactNode;
    subpages?: typeof CUSTOMER_SERVICE_SUBPAGES;
  }

  // 预定义的功能代理列表
  const FUNCTION_AGENTS: FunctionAgent[] = [
    {
      id: 'finance',
      name: '财务助理',
      description: 'Handles financial transactions',
      icon: '/sider-bar-icon/财务助理.png',
    },
    {
      id: 'customerService',
      name: '客服助理',
      description: 'Customer service assistant',
      icon: '/sider-bar-icon/客服助理.png',
      subpages: CUSTOMER_SERVICE_SUBPAGES,
    },
    {
      id: 'sales',
      name: '销售助理',
      description: 'Handles sales inquiries',
      icon: '/sider-bar-icon/销售助理.png',
    },
    {
      id: 'operation',
      name: '运营助理',
      description: 'Handles operation inquiries',
      icon: '/sider-bar-icon/运营助理.png',
    },
    {
      id: 'hr',
      name: '人力资源助理',
      description: 'Manages recruitment and employee records',
      icon: '/sider-bar-icon/人力资源助理.png',
    },
    {
      id: 'marketing',
      name: '市场助理',
      description: 'Supports marketing campaigns and analytics',
      icon: '/sider-bar-icon/市场助理.png',
    },
    {
      id: 'tech-support',
      name: '技术支持助理',
      description: 'Provides technical troubleshooting assistance',
      icon: '/sider-bar-icon/技术支持助理.png',
    },
    {
      id: 'content',
      name: '内容创作助理',
      description: 'Creates and edits marketing content',
      icon: '/sider-bar-icon/内容创作助理.png',
    },
    {
      id: 'data',
      name: '数据分析助理',
      description: 'Analyzes business data and generates reports',
      icon: '/sider-bar-icon/数据分析助理.png',
    },
    {
      id: 'legal',
      name: '法务助理',
      description: 'Assists with legal documentation and compliance',
      icon: '/sider-bar-icon/法务助理.png',
    },
    {
      id: 'admin',
      name: '行政助理',
      description: 'Handles office management and scheduling',
      icon: '/sider-bar-icon/行政助理.png',
    },
    {
      id: 'project',
      name: '项目管理助理',
      description: 'Supports project planning and execution',
      icon: '/sider-bar-icon/项目管理助理.png',
    },
    {
      id: 'research',
      name: '研发助理',
      description: 'Assists with product research and development',
      icon: '/sider-bar-icon/研发助理.png',
    },
    {
      id: 'logistics',
      name: '物流助理',
      description: 'Coordinates supply chain and delivery operations',
      icon: '/sider-bar-icon/物流助理.png',
    },
  ].map((agent) => ({
    ...agent,
    icon: <img src={agent.icon} className="h-7 w-7" />,
  }));

  const handleSubPageClick = (
    agentId: string,
    { id: subPageId, path: subPagePath },
  ) => {
    localStorage.setItem('agentType', agentId);
    router.push(`${subPagePath}?agentType=${agentId}&subPage=${subPageId}`);
    // // 如果是 知识库 子页面，导航到知识库页面
    // if (subPageId === 'rag') {
    //   router.push(`/knowledge?agentType=${agentId}&subPage=${subPageId}`);
    // } else {
    //   router.push(`/dashboard?agentType=${agentId}&subPage=${subPageId}`);
    // }
  };

  return (
    <Sidebar
      collapsible="icon"
      className="border-r-0 bg-background/95 backdrop-blur-sm [&::-webkit-scrollbar]:hidden [-ms-overflow-style:'none'] [scrollbar-width:'none']"
      {...props}
    >
      <SidebarHeader className="px-2 py-2">
        <div className="flex h-[40px] items-center px-1 relative">
          <Link href="/">
            {/* ronqi */}
            <RonqiLogo />
          </Link>
          {state !== 'collapsed' && (
            <div className="ml-2 transition-all duration-200 ease-in-out whitespace-nowrap"></div>
          )}
          <div className="ml-auto flex items-center gap-2">
            {state !== 'collapsed' && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <SidebarTrigger className="h-8 w-8" />
                </TooltipTrigger>
                <TooltipContent>Toggle sidebar (CMD+B)</TooltipContent>
              </Tooltip>
            )}
            {isMobile && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    onClick={() => setOpenMobile(true)}
                    className="h-8 w-8 flex items-center justify-center rounded-md hover:bg-accent"
                  >
                    <Menu className="h-4 w-4" />
                  </button>
                </TooltipTrigger>
                <TooltipContent>Open menu</TooltipContent>
              </Tooltip>
            )}
          </div>
        </div>
      </SidebarHeader>
      <SidebarContent className="[&::-webkit-scrollbar]:hidden [-ms-overflow-style:'none'] [scrollbar-width:'none'] p-[10px]">
        {FUNCTION_AGENTS.map((agent) => (
          <div key={agent.id}>
            <div
              className={cn(
                'bg-card rounded-lg cursor-pointer hover:bg-accent transition-colors',
                state === 'collapsed' ? 'p-1 ' : 'p-4',
                agent.id === currentAgentType
                  ? 'ring-2 ring-primary/70 bg-primary/10'
                  : '',
              )}
              onClick={() => {
                localStorage.setItem('agentType', agent.id);
                router.push(`/dashboard?agentType=${agent.id}`);
              }}
            >
              {state !== 'collapsed' ? (
                <>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center">
                      <span className="mr-2">{agent.icon}</span>
                      <h3 className="font-medium truncate">{agent.name}</h3>
                    </div>
                    {agent.subpages && (
                      <ChevronDown
                        className={cn(
                          'h-4 w-4 transition-transform duration-200 cursor-pointer hover:bg-accent-foreground/10 rounded p-0.5',
                          expandedAgent === agent.id ? 'rotate-180' : '',
                        )}
                        // 添加这个点击事件
                        onClick={(e) => {
                          e.stopPropagation();
                          setExpandedAgent(
                            expandedAgent === agent.id ? null : agent.id,
                          );
                        }}
                      />
                    )}
                  </div>
                </>
              ) : (
                <div className="flex justify-center">{agent.icon}</div>
              )}
            </div>

            {/* 子页面菜单 - 只在展开状态且有子页面时显示 */}
            {agent.subpages && state !== 'collapsed' && (
              <div
                className={`mt-2 space-y-1 overflow-hidden transition-all duration-300 ease-in-out ${
                  expandedAgent === agent.id
                    ? 'max-h-96 opacity-100'
                    : 'max-h-0 opacity-0'
                }`}
              >
                {CUSTOMER_SERVICE_SUBPAGES.map((subPage, index) => (
                  <div
                    key={subPage.id}
                    className={cn(
                      // 移除了 ml-4，改为使用 padding 和 margin 来控制
                      'relative mx-2 rounded-md cursor-pointer transition-all duration-200 py-2 px-4 transform',
                      // 选中状态的完整覆盖样式
                      currentAgentType === agent.id &&
                        currentSubPage === subPage.id
                        ? 'bg-primary/10 border border-primary/30 shadow-md shadow-primary/20'
                        : 'bg-card/50 hover:bg-accent border border-transparent',
                      // 动画效果
                      expandedAgent === agent.id
                        ? `translate-y-0 opacity-100 transition-delay-[${index * 50}ms]`
                        : 'translate-y-[-10px] opacity-0',
                    )}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleSubPageClick(agent.id, subPage);
                    }}
                  >
                    {/* 内容区域 */}
                    <div className="relative pl-3">
                      <h4 className="text-sm font-medium truncate">
                        {subPage.name}
                      </h4>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
        {/* <SidebarGroup>
          <Link href="/dashboard">
            <SidebarMenuButton className={cn({
              'bg-accent text-accent-foreground font-medium': pathname === '/dashboard',
            })}>
              <Plus className="h-4 w-4 mr-1" />
              <span className="flex items-center justify-between w-full">
                New Task
              </span>
            </SidebarMenuButton>
          </Link>
          {!flagsLoading && customAgentsEnabled && (
            <SidebarMenu>
              <Collapsible
                defaultOpen={pathname?.includes('/agents')}
                className="group/collapsible"
              >
                <SidebarMenuItem>
                  <CollapsibleTrigger asChild>
                    <SidebarMenuButton
                      tooltip="Agents"
                    >
                      <Bot className="h-4 w-4 mr-1" />
                      <span>Agents</span>
                      <ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
                    </SidebarMenuButton>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    <SidebarMenuSub>
                      <SidebarMenuSubItem>
                        <SidebarMenuSubButton className={cn('pl-3', {
                          'bg-accent text-accent-foreground font-medium': pathname === '/agents' && searchParams.get('tab') === 'marketplace',
                        })} asChild>
                          <Link href="/agents?tab=marketplace">
                            <span>Explore</span>
                          </Link>
                        </SidebarMenuSubButton>
                      </SidebarMenuSubItem>
                      <SidebarMenuSubItem>
                        <SidebarMenuSubButton className={cn('pl-3', {
                          'bg-accent text-accent-foreground font-medium': pathname === '/agents' && (searchParams.get('tab') === 'my-agents' || searchParams.get('tab') === null),
                        })} asChild>
                          <Link href="/agents?tab=my-agents">
                            <span>My Agents</span>
                          </Link>
                        </SidebarMenuSubButton>
                      </SidebarMenuSubItem>
                      <SidebarMenuSubItem>
                        <SidebarMenuSubButton 
                          onClick={() => setShowNewAgentDialog(true)}
                          className="cursor-pointer pl-3"
                        >
                          <span>New Agent</span>
                        </SidebarMenuSubButton>
                      </SidebarMenuSubItem>
                    </SidebarMenuSub>
                  </CollapsibleContent>
                </SidebarMenuItem>
              </Collapsible>
            </SidebarMenu>
          )}
          {!flagsLoading && customAgentsEnabled && (
            <Link href="/settings/credentials">
              <SidebarMenuButton className={cn({
                'bg-accent text-accent-foreground font-medium': pathname === '/settings/credentials',
              })}>
                <Plug className="h-4 w-4 mr-1" />
                <span className="flex items-center justify-between w-full">
                  Integrations
                </span>
              </SidebarMenuButton>
            </Link>
          )}
        </SidebarGroup>
        <NavAgents /> */}
      </SidebarContent>
      {/* {state !== 'collapsed' && (
        <div className="px-3 py-2">
          <CTACard />
        </div>
      )} */}
      <SidebarFooter>
        {state === 'collapsed' && (
          <div className="mt-2 flex justify-center">
            <Tooltip>
              <TooltipTrigger asChild>
                <SidebarTrigger className="h-8 w-8" />
              </TooltipTrigger>
              <TooltipContent>Expand sidebar (CMD+B)</TooltipContent>
            </Tooltip>
          </div>
        )}
        <NavUserWithTeams user={user} />
      </SidebarFooter>
      <SidebarRail />
      <AlertDialog
        open={showNewAgentDialog}
        onOpenChange={setShowNewAgentDialog}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Create New Agent</AlertDialogTitle>
            <AlertDialogDescription>
              This will create a new agent with a default name and description.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleCreateNewAgent}>
              Create
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Sidebar>
  );
}
